<template>
  <el-dialog title="角色授权" :visible.sync="dialogFormVisible">
    <!--
      tree组件
      data 数据
      show-checkbox 是否显示复选框
      node-key 用来指定数据中唯一标识字段
      default-expanded-keys 默认展开的节点id
      default-checked-keys 默认选中的节点
    -->
    <el-tree
      :data="rights"
      ref="tree"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-checked-keys="defaultChecked"
      :props="defaultProps">
    </el-tree>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click.prevent="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getRightsList } from '@/api/rights'
import { updateRightsByRoleId } from '@/api/role'
export default {
  name: 'RoleEditRights',
  data () {
    return {
      dialogFormVisible: false,
      rights: [],
      defaultChecked: [], // 默认选中的节点id数组
      defaultProps: {
        children: 'children', // 告诉tree你的哪个字段是子节点数组
        label: 'authName' // 告诉tree你的数据中哪个字段是节点的文本
      },
      role: {}
    }
  },
  methods: {
    showDialog (role) {
      this.role = role
      this.dialogFormVisible = true
      this.loadRights()
      this.getRights(role.children)
    },
    getRights (roleRights) {
      const tmp = []
      roleRights.forEach(first => {
        first.children.forEach(second => {
          second.children.forEach(third => tmp.push(third.id))
        })
      })
      this.defaultChecked = tmp
    },
    async loadRights () {
      const { data, meta } = await getRightsList('tree')
      if (meta.status === 200) {
        this.rights = data
      }
    },
    async handleSubmit () {
      const tree = this.$refs.tree
      const rids = [...tree.getCheckedKeys(), ...tree.getHalfCheckedKeys()].join(',')
      const { meta } = await updateRightsByRoleId(this.role.id, rids)
      if (meta.status === 200) {
        this.dialogFormVisible = false
        this.$emit('edit-rights-success')
        this.$message({
          type: 'success',
          message: '角色授权成功'
        })
      }
    }
  }
}
</script>
<style scoped>
</style>
